const blogmodel = require('../model/blog.js')
const tagmodel = require('../model/tag.js')


const showindex = async(ctx) => {

	await ctx.render('index', {
		"active": "首页" || '',
		"title": "顶上前端_追求源于热爱" || '',
		"keywords": "顶上前端,ariza全栈,",
		"description": "追求源于热爱，ariza全栈开发，你指间跃动的闪光，是我一生不变的信仰"
	})
}
const kefus = async(ctx) => {

	await ctx.render('kefu', {
		"active": "客服" || '',
		"title": "宇商建站" || '',
	})
}

const list = async(ctx) => {
	let all = {}
	var page = ctx.query.page || 1;
	var data
	var data2
	if(!ctx.query.searchValue){
		data={}
	}else{
		const reg = new RegExp(ctx.query.searchValue, 'i')
		data = {
	    $or: [
	      { title: { $regex: reg } }
	    ]
	  }
	}
	let taglist = await tagmodel.findnormal(data2)
	var pageSize = 5
	let visiblepage = 5
	var skipnum = (page - 1) * pageSize
	var sort = {
		"_id": -1
	}
	let doc = await blogmodel.findall(data, skipnum, pageSize, sort)
	let count = await blogmodel.countall()
	let maxpage = Math.ceil(count / pageSize) || 0

	let proge = prohabitpage(maxpage, visiblepage, page)
 	let doc2 = await blogmodel.findnormal(all,5)
	await ctx.render('list', {
		'page': page,
		"pagecount": proge,
		"alllist":doc2,
		"taglist":taglist,
		"alllist2": doc,
		"active": "博客" || '',
		"title": "博客列表" || '',
		"keywords":"顶上前端,ariza全栈,",
        "description":"追求源于热爱，ariza全栈开发，你指间跃动的闪光，是我一生不变的信仰",
		"login": ctx.session.login == "1" ? true : false,
		"username": ctx.session.login == "1" ? ctx.session.username : "",
		"avatar": ctx.session.avatar || '',

	})
}

const adminlist = async(ctx) => {
	var pageNum = ctx.request.body.pageNum || 1;
	const reg = new RegExp(ctx.request.body.searchValue, 'i')
	let data 
	if(ctx.request.body.searchValue==''){
		data={}
	}else{
		data = {
	    $or: [
	      { title: { $regex: reg } }
	    ]
	  }
	}
	var pageSize = Number(ctx.request.body.pageSize)
	var skipnum = Number((pageNum - 1) * pageSize)
	var sort = {
		"datetime": -1
	}
	let doc = await blogmodel.findall(data, skipnum, pageSize, sort)
	let count = await blogmodel.countall()
	ctx.body={
		data:doc,
		count:count
	}
}


const prohabitpage = (maxpage, visiblepage, page) => {
	var lowPage = 1;
	var highPage = maxpage;
	var pageArr = [];
	if(maxpage > visiblepage) {
		var sub = Math.ceil(visiblepage / 2);

		if(page > sub && page < maxpage - sub + 1) {
			lowPage = page - sub;
			highPage = page + sub - 1;
		} else if(page <= sub) {
			lowPage = 1;
			highPage = visiblepage;
		} else {
			lowPage = maxpage - visiblepage + 1;
			highPage = maxpage;
		}
	}

	while(lowPage <= highPage) {
		pageArr.push(lowPage);
		lowPage++;
	}

	return pageArr;
}

module.exports = {
	showindex,
	kefus,
	list,
	adminlist
}